from collections import defaultdict
from datetime import datetime

from flask import Blueprint, request
from sqlalchemy import null, or_, and_
from sqlalchemy.exc import SQLAlchemyError
from response import success_response,error_response

from extension import db
from models import Letter, Account

column_bp = Blueprint('column', __name__)


@column_bp.route('/api/column/writeLetter',methods=['POST',])
def writeLetter():
    letter = Letter()
    letter.letterId = 0
    letter.sender = request.json.get('sender')
    letter.recipient = request.json.get('recipient')
    letter.msgType = request.json.get('msgType')
    letter.letter = request.json.get('letter')
    letter.view = 0
    letter.sendTime = datetime.now()
    try:
        db.session.add(letter)
        db.session.commit()
        return success_response()
    except SQLAlchemyError as e:
        db.session.rollback()
        return error_response()

@column_bp.route('/api/column/<username>',methods=['GET',])
def getColumnList(username):
    try:
        letters = Letter.query.filter(or_(Letter.sender == username, Letter.recipient == username, Letter.msgType==2)).all()
        if letters:
            result = [
                {
                    "msgType": letter.msgType,
                    "view": letter.view,
                    "sender": letter.sender,
                    "recipient": letter.recipient,
                    "letterId": letter.letterId,
                    "sendTime": letter.sendTime.strftime("%Y-%m-%d")
                }for letter in letters
            ]
            final_result = []
            sender_dict = defaultdict(list)
            for letter_info in result:
                if letter_info["msgType"] == 1:
                    if letter_info["sender"] == username:
                        continue
                    else:
                        sender_dict[letter_info["sender"]].append(letter_info)
                else:
                    final_result.append(letter_info)
            for sender, letters_info in sender_dict.items():
                max_id_letter = max(letters_info, key=lambda x: x["letterId"])
                final_result.append(max_id_letter)
            return {
                "code": "SUCCESS",
                "message": "SUCCESS",
                "data": {"sysMsgs": final_result}
            }
        else:
            return error_response()
    except SQLAlchemyError as e:
        return error_response()


@column_bp.route('/api/column/letter',methods=['GET',])
def getLetter():
    try:
        letter = Letter.query.get(request.args.get('letterId'))
        if letter:
            letter.view = 1
            db.session.commit()
            if letter.msgType == 0:
                parts = letter.letter.split('/')
                title = parts[0]
                message = parts[1]
                return {
                    "code": "SUCCESS",
                    "message": "SUCCESS",
                    "data":{
                        "letterId": letter.letterId,
                        "sender": letter.sender,
                        "message": message,
                        "title": title,
                        "view": 1,
                        "recipient": letter.recipient,
                        "msgType": letter.msgType,
                        "sendTime": letter.sendTime
                    }
                }
            else:
                return {
                    "code": "SUCCESS",
                    "message": "SUCCESS",
                    "data": {
                        "letterId": letter.letterId,
                        "sender": letter.sender,
                        "message": letter.letter,
                        "view": 1,
                        "recipient": letter.recipient,
                        "msgType": letter.msgType,
                        "sendTime": letter.sendTime
                    }
                }
        else:
            return error_response()
    except SQLAlchemyError as e:
        db.session.rollback()
        return error_response()


@column_bp.route('/api/column/view/<username>',methods=['GET',])
def getView(username):
    try:
        letters = Letter.query.filter(and_(Letter.view == 0, Letter.recipient == username)).all()
        if letters:
            return {
                "code": "SUCCESS",
                "message": "SUCCESS",
                "data": len(letters)
            }
        else:
            return{
                "code": "SUCCESS",
                "message": "SUCCESS",
                "data": 0
            }
    except SQLAlchemyError as e:
        return error_response()

@column_bp.route('/api/column/consultMsg/<username>/<msgType>',methods=['GET',])
def getConsult(username, msgType):
    try:
        letters = Letter.query.filter(and_(Letter.msgType == msgType, or_(Letter.recipient == username, Letter.sender == username))).order_by(Letter.letterId).all()
        if letters:
            for letter in letters:
                letter.view = 1
            db.session.commit()
            result = [
                {
                    "letterId": letter.letterId,
                    "sender": letter.sender,
                    "letter": letter.letter,
                    "view": 1,
                    "recipient": letter.recipient,
                    "msgType": letter.msgType,
                    "sendTime": letter.sendTime
                }for letter in letters
            ]
            return {
                "code": "SUCCESS",
                "message": "SUCCESS",
                "data":{
                    "consultation": result
                }
            }
        else:
            return error_response()
    except SQLAlchemyError as e:
        db.session.rollback()
        return error_response()